package com.data.modules.system.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.data.common.api.dto.message.MessageDTO;
import com.data.common.constant.enums.ApprovaStateEnum;
import com.data.common.system.api.ISysBaseAPI;
import com.data.common.system.vo.LoginUser;
import com.data.common.util.ConvertUtils;
import com.data.common.util.PasswordUtil;
import com.data.common.util.RestUtil;
import com.data.config.thirdapp.ThirdAppConfig;
import com.data.modules.system.entity.SysThirdAccount;
import com.data.modules.system.entity.SysUser;
import com.data.modules.system.service.ISysThirdAccountService;
import com.data.modules.system.service.ISysUserService;
import com.data.modules.system.service.IThirdAppService;
import com.data.modules.system.vo.thirdapp.SyncInfoVo;
import com.jeecg.dingtalk.api.core.vo.AccessToken;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 第三方App对接：飞书实现类
 */
@SuppressWarnings("ALL")
@Slf4j
@Service
public class ThirdAppFeiShutalkServiceImpl implements IThirdAppService {

    @Autowired
    ThirdAppConfig thirdAppConfig;
    @Autowired
    private ISysUserService sysUserService;
    @Autowired
    private ISysThirdAccountService sysThirdAccountService;
    @Autowired
    private ISysBaseAPI sysBaseAPI;
    // 第三方APP类型，当前固定为 fly_book
    public final String THIRD_TYPE = ThirdAppConfig.FLYBOOK.toLowerCase();

    /**
     * 获取token
     *
     * @return
     */
    @Override
    public String getAccessToken() {
        String appId = "cli_a2a5be63077bd00b";
        String appSecret = "mbc3Lapjbet7uafLM3ZnMf6K2UxydJ0B";
        AccessToken accessToken = null;
        String strUrl = "https://open.feishu.cn/open-apis/auth/v3/app_access_token/internal";
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.valueOf(MediaType.APPLICATION_JSON_UTF8_VALUE));
        HashMap<String, String> params = new HashMap<>();
        params.put("app_id", appId);
        params.put("app_secret", appSecret);
        JSONObject response = RestUtil.request(strUrl, HttpMethod.POST, headers, null, JSON.toJSON(params), JSONObject.class).getBody();
        /**
         * 请求飞书成功 返回 errcode 对应的是 token生效时间
         * 请求飞书失败 返回 errcode 对应的是 服务端错误码
         *
         * https://open.feishu.cn/document/ukTMukTMukTM/ugjM14COyUjL4ITN 找相应错误码解决问题
         *
         * */
        int errcode;
        if (response != null && ObjectUtil.equal(response.get("code"), 0)) {
            String access_token = response.getString("app_access_token");
            errcode = response.getIntValue("expire");
            accessToken = new AccessToken(access_token, errcode);
            log.info("[ACCESS_TOKEN] 获取ACCESS_TOKEN成功:{}", accessToken);
        } else {
            errcode = response.getIntValue("code");
            String errmsg = response.getString("errmsg");
            log.info("[ACCESS_TOKEN] 获取ACCESS_TOKEN失败 errcode:{} errmsg:{}", errcode, errmsg);
        }
        if (accessToken != null) {
            return accessToken.getAccessToken();
        }
        log.warn("获取AccessToken失败");
        return null;
    }

    @Override
    public boolean syncLocalDepartmentToThirdApp(String ids) {
        return false;
    }


    @Override
    public SyncInfoVo syncLocalUserToThirdApp(String ids) {
        return null;
    }

    @Override
    public SyncInfoVo syncThirdAppUserToLocal() {
        return null;
    }

    @Override
    public int removeThirdAppUser(List<String> userIdList) {
        return 0;
    }

    @Override
    public boolean sendMessage(MessageDTO message, boolean verifyConfig) {
        return false;
    }

    @Override
    public boolean sendMessage(MessageDTO message) {
        return false;
    }


    public JSONObject getRequest(String strUrl, Map<String, String> params, HttpHeaders headers) {
        JSONObject response = RestUtil.request(strUrl, HttpMethod.GET, headers, null, JSON.toJSON(params), JSONObject.class).getBody();
        return response;
    }

    public JSONObject postRequest(String strUrl, Map<String, String> params, HttpHeaders headers) {
        JSONObject response = RestUtil.request(strUrl, HttpMethod.POST, headers, null, JSON.toJSON(params), JSONObject.class).getBody();
        return response;
    }

    /***
     * 同步飞书数据用户
     * @return
     */
    @Override
    public SyncInfoVo syncThirdAppDepartmentToLocal(String ids) {
        SyncInfoVo syncInfo = new SyncInfoVo();
        String accessToken = getAccessToken();
        if (accessToken == null) {
            return syncInfo;
        } else {
            accessToken = "Bearer " + accessToken;
        }
        String strUrl = "https://open.feishu.cn/open-apis/contact/v3/users/find_by_department?department_id=0";
        Map<String, String> params = new HashMap<>();
        params.put("department_id", "0");
        HttpHeaders headers = new HttpHeaders();
        headers.set("Authorization", accessToken);
        // 获取企业微信所有的员工
        JSONObject departments = getRequest(strUrl, null, headers);
        if (departments == null && ObjectUtil.isEmpty(departments.get("data"))) {
            return syncInfo;
        }
        Object itemsInfo = departments.get("data");
        JSONObject items = (JSONObject) JSON.toJSON(itemsInfo);
        //查询所有飞书用户
        List<Object> resultList = (List<Object>) items.get("items");
        //获取本地用户
        List<SysUser> sysUsersList = sysUserService.list();
        //获取本地逻辑删除的用户
        List<SysUser> sysUsersDeletedList = sysUserService.queryLogicDeleted();
        //循环飞书的用户转换成为系统用户对象进行 更新创建操作
        for (Object bookUser : resultList) {
            //将obj对象转成map
            Map<String, Object> map = JSONObject.parseObject(JSONObject.toJSONString(bookUser), Map.class);
            SysThirdAccount sysThirdAccount = sysThirdAccountService.getOneByThirdUserId(String.valueOf(map.get("user_id")), THIRD_TYPE);
            //获取存在系统的用户
            List<SysUser> collect = sysUsersList.stream()
                    .filter(user -> {
                                String mobile = String.valueOf(map.get("mobile")).replace("+86", "");
                                return mobile.equals(user.getPhone());
                            }
                    ).collect(Collectors.toList());

            //系统已经删除的用户
            List<SysUser> deleteUser = sysUsersDeletedList.stream()
                    .filter(user -> {
                                String mobile = String.valueOf(map.get("mobile")).replace("+86", "");
                                return mobile.equals(user.getPhone());
                            }
                    ).collect(Collectors.toList());
            if (deleteUser != null && deleteUser.size() > 0) {
                continue;
            }
            if (collect != null && collect.size() > 0) {
                SysUser sysUserTemp = collect.get(0);
                // 循环到此说明用户匹配成功，进行更新操作
                SysUser updateSysUser = this.dtUserToSysUser(map, sysUserTemp);
                try {
                    sysUserService.updateById(updateSysUser);
                    String str = String.format("用户 %s(%s) 更新成功！", updateSysUser.getRealname(), updateSysUser.getUsername());
                    syncInfo.addSuccessInfo(str);
                } catch (Exception e) {
                    this.syncUserCollectErrInfo(e, map, syncInfo);
                }
                //第三方账号关系表
                this.thirdAccountSaveOrUpdate(sysThirdAccount, updateSysUser.getId(), String.valueOf(map.get("user_id")));
            } else {
                // 如果没有匹配到用户，则走创建逻辑
                SysUser newSysUser = this.dtUserToSysUser(map);
                try {
                    sysUserService.save(newSysUser);
                    String str = String.format("用户 %s(%s) 创建成功！", newSysUser.getRealname(), newSysUser.getUsername());
                    syncInfo.addSuccessInfo(str);
                } catch (Exception e) {
                    this.syncUserCollectErrInfo(e, map, syncInfo);
                }
                //第三方账号关系表
                this.thirdAccountSaveOrUpdate(null, newSysUser.getId(), String.valueOf(map.get("user_id")));
            }

        }
        return syncInfo;
    }

    /**
     * 【同步用户】收集同步过程中的错误信息
     */
    private boolean syncUserCollectErrInfo(Exception e, Map<String, Object> map, SyncInfoVo syncInfo) {
        String msg;
        if (e instanceof DuplicateKeyException) {
            msg = e.getCause().getMessage();
        } else {
            msg = e.getMessage();
        }
        String str = String.format("用户 %s(%s) 同步失败！错误信息：%s", String.valueOf(map.get("user_id")), String.valueOf(map.get("name")), msg);
        syncInfo.addFailInfo(str);
        return false;
    }

    /**
     * 【同步用户】将【飞书】的User对象转为SysUser（更新旧用户）
     */
    private SysUser dtUserToSysUser(Map<String, Object> map, SysUser oldSysUser) {
        SysUser sysUser = new SysUser();
        BeanUtils.copyProperties(oldSysUser, sysUser);
        sysUser.setRealname(String.valueOf(map.get("name")));
        //飞书没有座机号码
        //sysUser.setTelephone(String.valueOf(map.get("name")));
        // 因为唯一键约束的原因，如果原数据和旧数据相同，就不更新
        if (ConvertUtils.isNotEmpty(map.get("email")) && !String.valueOf(map.get("email")).equals(sysUser.getEmail())) {
            sysUser.setEmail(String.valueOf(map.get("email")));
        } else {
            sysUser.setEmail(null);
        }
        // 因为唯一键约束的原因，如果原数据和旧数据相同，就不更新
        if (ConvertUtils.isNotEmpty(map.get("mobile")) && !String.valueOf(map.get("mobile")).replace("+86", "").equals(sysUser.getPhone())) {
            sysUser.setPhone(String.valueOf(map.get("mobile")).replace("+86", ""));
        } else {
            sysUser.setPhone(null);
        }
        sysUser.setWorkNo(null);
        // --- 飞书没有逻辑删除功能
        // sysUser.getDelFlag()
        // --- 飞书没有冻结、启用禁用功能
        // sysUser.getStatus()
        return sysUser;
    }

    /**
     * 保存或修改第三方登录表
     *
     * @param sysThirdAccount 第三方账户表对象，为null就新增数据，否则就修改
     * @param sysUserId       本地系统用户ID
     * @param dtUserId        飞书用户ID
     */
    private void thirdAccountSaveOrUpdate(SysThirdAccount sysThirdAccount, String sysUserId, String dtUserId) {
        if (sysThirdAccount == null) {
            sysThirdAccount = new SysThirdAccount();
            sysThirdAccount.setSysUserId(sysUserId);
            sysThirdAccount.setStatus(1);
            sysThirdAccount.setDelFlag(0);
            sysThirdAccount.setThirdType(THIRD_TYPE);
        }
        sysThirdAccount.setSysUserId(sysUserId);
        sysThirdAccount.setThirdUserId(dtUserId);
        sysThirdAccountService.saveOrUpdate(sysThirdAccount);
    }

    /**
     * 【同步用户】将【飞书】的User对象转为SysUser（创建新用户）
     */
    private SysUser dtUserToSysUser(Map<String, Object> map) {
        SysUser sysUser = new SysUser();
        sysUser.setDelFlag(0);
        // 通过 username 来关联
        sysUser.setUsername(String.valueOf(map.get("user_id")));
        // 密码默认为 “123456”，随机加盐
        String password = "123456", salt = ConvertUtils.randomGen(8);
        String passwordEncode = PasswordUtil.encrypt(sysUser.getUsername(), password, salt);
        sysUser.setSalt(salt);
        sysUser.setPassword(passwordEncode);
        // update-begin--Author:liusq Date:20210713 for：飞书同步到本地的人员没有状态，导致同步之后无法登录 #I3ZC2L
        sysUser.setStatus(1);
        // update-end--Author:liusq Date:20210713 for：飞书同步到本地的人员没有状态，导致同步之后无法登录 #I3ZC2L
        return this.dtUserToSysUser(map, sysUser);
    }

    /**
     * TODO将接口异步处理
     *
     * @param responseStr
     */
    public void flyBookApprovalCallback(JSONObject responseStr) {
        log.info("===flyBookApprovalCallback===responseStr:{}",responseStr);
        /*HlContract one = hlContractService.lambdaQuery()
                .eq(HlContract::getSpNo, responseStr.get("instance_code")).one();
        if (ObjectUtil.isNotEmpty(responseStr)&& one.getSpStatus()!=2) {
            String accessToken = getAccessToken();
            if (ObjectUtil.isNotEmpty(accessToken) ) {
                accessToken = "Bearer " + accessToken;
            }
            String getApprovalUrl = "https://www.feishu.cn/approval/openapi/v2/instance/get";
            Map<String, String> params = new HashMap<>();
            params.put("instance_code", responseStr.get("instance_code").toString());
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", accessToken);
            // 获取企业微信所有的员工
            JSONObject approvalInfor = postRequest(getApprovalUrl, params, headers);
            log.info("===flyBookApprovalCallback===approvalInfor:{}",approvalInfor);
            //获取审批信息
            JSONObject data = approvalInfor.getJSONObject("data");
            JSONArray taskList  = data.getJSONArray("task_list");
            List<LinkedHashMap> collect = (List<LinkedHashMap>) taskList.stream()
                    .map(x -> BeanUtil.copyProperties(x, LinkedHashMap.class)).collect(Collectors.toList());
            List<String> node = collect.stream().map(p -> p.get("node_id").toString()).distinct().collect(Collectors.toList());
            Map<String, List<LinkedHashMap>> nodeMap = collect
                    .stream().collect(Collectors.groupingBy(p -> p.get("node_id").toString(), Collectors.toList()));
            StringBuffer stringBuffer = new StringBuffer();
            for (String s : node) {
                for (LinkedHashMap<String,Object>  task : nodeMap.get(s)) {
                    oneNode(stringBuffer,task);
                    int i = nodeMap.get(s).indexOf(task);
                    if (i!= nodeMap.get(s).size()-1){
                        stringBuffer.append(",");
                    }
                }
                stringBuffer.append("-->");
            }
            stringBuffer.replace(stringBuffer.length()-"-->".length(),stringBuffer.length(),"");

            if (ObjectUtil.equal(data.get("status"),ApprovaStateEnum.APPROVED.getInfo())){
                hlContractService.lambdaUpdate()
                        .set(HlContract::getSpRecord, stringBuffer.toString())
                        .set(HlContract::getSpStatus, 2)
                        .eq(HlContract::getId, one.getId()).update();
            }else if (ObjectUtil.equal(data.get("status"),ApprovaStateEnum.REJECTED.getInfo())){
                hlContractService.lambdaUpdate()
                        .set(HlContract::getSpStatus, 3)
                        .set(HlContract::getSpRecord, stringBuffer.toString())
                        .eq(HlContract::getId, one.getId()).update();
            }else {
                hlContractService.lambdaUpdate()
                        .set(HlContract::getSpRecord, stringBuffer.toString())
                        .eq(HlContract::getId, one.getId()).update();
            }
        }else{
            log.info("======flyBookApprovalCallback======飞书回调接口参数是空！！");
        }*/
    }

    public static void main(String[] args) {

        JSONObject responseStr=JSON.parseObject("{\n" +
                "    \"msg\": \"\",\n" +
                "    \"code\": 0,\n" +
                "    \"data\": {\n" +
                "        \"approval_code\": \"60A0D11A-F8F5-41A7-AB88-539EB0831DE4\",\n" +
                "        \"approval_name\": \"合同申请\",\n" +
                "        \"comment_list\": [],\n" +
                "        \"department_id\": \"\",\n" +
                "        \"end_time\": 1648450426448,\n" +
                "        \"form\": \"[{\\\"id\\\":\\\"widget16474168248790001\\\",\\\"name\\\":\\\"提交时间\\\",\\\"type\\\":\\\"date\\\",\\\"ext\\\":null,\\\"value\\\":\\\"2022-03-11T13:54:05Z\\\"},{\\\"id\\\":\\\"widget15995460603370001\\\",\\\"name\\\":\\\"合同名称\\\",\\\"type\\\":\\\"input\\\",\\\"ext\\\":null,\\\"value\\\":\\\"海南新盈科技(有限)公司框架协议20220311\\\"},{\\\"id\\\":\\\"widget16474169027270001\\\",\\\"name\\\":\\\"合同起始日\\\",\\\"type\\\":\\\"date\\\",\\\"ext\\\":null,\\\"value\\\":\\\"2022-02-22T00:00:00Z\\\"},{\\\"id\\\":\\\"widget16474169049770001\\\",\\\"name\\\":\\\"合同终止日\\\",\\\"type\\\":\\\"date\\\",\\\"ext\\\":null,\\\"value\\\":\\\"2023-02-21T00:00:00Z\\\"},{\\\"id\\\":\\\"widget16474169283220001\\\",\\\"name\\\":\\\"合作商\\\",\\\"type\\\":\\\"input\\\",\\\"ext\\\":null,\\\"value\\\":\\\"海南新盈科技(有限)公司\\\"},{\\\"id\\\":\\\"widget16474169397660001\\\",\\\"name\\\":\\\"合同类型\\\",\\\"type\\\":\\\"input\\\",\\\"ext\\\":null,\\\"value\\\":\\\"框架协议\\\"},{\\\"id\\\":\\\"widget16474169568600001\\\",\\\"name\\\":\\\"备注\\\",\\\"type\\\":\\\"input\\\",\\\"ext\\\":null,\\\"value\\\":\\\"无\\\"},{\\\"id\\\":\\\"widget15995462559070001\\\",\\\"name\\\":\\\"合同附件\\\",\\\"type\\\":\\\"attachmentV2\\\",\\\"ext\\\":\\\"https://mall-oss-pic.oss-cn-beijing.aliyuncs.com/20220311135404/海南新盈科技(有限)公司框架协议20220311_1646978044735.pdf\\\",\\\"value\\\":[\\\"https://lf3-approval-sign.bytetos.com/lark-approval-attachment/attachment/20220328/6942280201883615233/fc30b2e8-9f4f-4f68-8f75-0e7f84c851da.pdf?x-expires=1648493627\\\\u0026x-signature=1DmV23GcmZykAJLYuANxK1TOZDk%3D#/obj/obj.pdf\\\"]}]\",\n" +
                "        \"open_id\": \"ou_986df002fc6266c884e60babb10bfe40\",\n" +
                "        \"serial_number\": \"202203280003\",\n" +
                "        \"start_time\": 1648449474933,\n" +
                "        \"status\": \"APPROVED\",\n" +
                "        \"task_list\": [\n" +
                "            {\n" +
                "                \"end_time\": 1648449698370,\n" +
                "                \"id\": \"7080036585751707676\",\n" +
                "                \"node_id\": \"65d08d440616f07976fe9721c2924d0e\",\n" +
                "                \"node_name\": \"审批\",\n" +
                "                \"open_i d\": \"ou_2267cedbf6a6b1a376b6a23fbf152eb7\",\n" +
                "                \"start_time\": 1648449475066,\n" +
                "                \"status\": \"APPROVED\",\n" +
                "                \"type\": \"AND\",\n" +
                "                \"user_id\": \"42d91484\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"end_time\": 1648449698370,\n" +
                "                \"id\": \"7080036585751707676\",\n" +
                "                \"node_id\": \"65d08d440616f07976fe9721c2924d0e\",\n" +
                "                \"node_name\": \"审批\",\n" +
                "                \"open_i d\": \"ou_2267cedbf6a6b1a376b6a23fbf152eb7\",\n" +
                "                \"start_time\": 1648449475066,\n" +
                "                \"status\": \"APPROVED\",\n" +
                "                \"type\": \"AND\",\n" +
                "                \"user_id\": \"42d91484\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"end_time\": 1648449854055,\n" +
                "                \"id\": \"7080037544728985628\",\n" +
                "                \"node_id\": \"d600ccbc33a3012ba39677de4e9c570d\",\n" +
                "                \"node_name\": \"审批\",\n" +
                "                \"open_id\": \"ou_98512ee321276d2208f7ffbb6a758ad1\",\n" +
                "                \"start_time\": 1648449698460,\n" +
                "                \"status\": \"APPROVED\",\n" +
                "                \"type\": \"AND\",\n" +
                "                \"user_id\": \"g52aa41d\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"end_time\": 1648450426357,\n" +
                "                \"id\": \"7080038214299336707\",\n" +
                "                \"node_id\": \"a43b42db3c7d8442ed1210f023a73650\",\n" +
                "                \"node_name\": \"审批\",\n" +
                "                \"open_id\": \"ou_8ecf6a12a99018df1e49809aad67b3cb\",\n" +
                "                \"start_time\": 1648449854253,\n" +
                "                \"status\": \"APPROVED\",\n" +
                "                \"type\": \"AND\",\n" +
                "                \"user_id\": \"6f778bgd\"\n" +
                "            }\n" +
                "        ],\n" +
                "        \"timeline\": [\n" +
                "            {\n" +
                "                \"create_time\": 1648449474933,\n" +
                "                \"ext\": \"{}\",\n" +
                "                \"open_id\": \"ou_986df002fc6266c884e60babb10bfe40\",\n" +
                "                \"type\": \"START\",\n" +
                "                \"user_id\": \"fc6adf49\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"create_time\": 1648449698370,\n" +
                "                \"ext\": \"{}\",\n" +
                "                \"node_key\": \"APPROVAL_127729_219176\",\n" +
                "                \"open_id\": \"ou_2267cedbf6a6b1a376b6a23fbf152eb7\",\n" +
                "                \"task_id\": \"7080036585751707676\",\n" +
                "                \"type\": \"PASS\",\n" +
                "                \"user_id\": \"42d91484\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"create_time\": 1648449854055,\n" +
                "                \"ext\": \"{}\",\n" +
                "                \"node_key\": \"APPROVAL_530076_2947606\",\n" +
                "                \"open_id\": \"ou_98512ee321276d2208f7ffbb6a758ad1\",\n" +
                "                \"task_id\": \"7080037544728985628\",\n" +
                "                \"type\": \"PASS\",\n" +
                "                \"user_id\": \"g52aa41d\"\n" +
                "            },\n" +
                "            {\n" +
                "                \"create_time\": 1648450426357,\n" +
                "                \"ext\": \"{}\",\n" +
                "                \"node_key\": \"APPROVAL_202881_1137908\",\n" +
                "                \"open_id\": \"ou_8ecf6a12a99018df1e49809aad67b3cb\",\n" +
                "                \"task_id\": \"7080038214299336707\",\n" +
                "                \"type\": \"PASS\",\n" +
                "                \"user_id\": \"6f778bgd\"\n" +
                "            }\n" +
                "        ],\n" +
                "        \"user_id\": \"fc6adf49\",\n" +
                "        \"uuid\": \"\"\n" +
                "    }\n" +
                "}");

        JSONObject data = responseStr.getJSONObject("data");
        JSONArray taskList  = data.getJSONArray("task_list");
       List<LinkedHashMap> collect = (List<LinkedHashMap>) taskList.stream()
                .map(x -> BeanUtil.copyProperties(x, LinkedHashMap.class)).collect(Collectors.toList());
        List<String> node = collect.stream().map(p -> p.get("node_id").toString()).distinct().collect(Collectors.toList());
        Map<String, List<LinkedHashMap>> nodeMap = collect
                .stream().collect(Collectors.groupingBy(p -> p.get("node_id").toString(), Collectors.toList()));
        StringBuffer stringBuffer = new StringBuffer();
        for (String s : node) {
            for (LinkedHashMap<String,Object>  task : nodeMap.get(s)) {
                //oneNode(stringBuffer,task);
                int i = nodeMap.get(s).indexOf(task);
                if (i!= nodeMap.get(s).size()-1){
                    stringBuffer.append(",");
                }
            }
            stringBuffer.append("-->");
        }
    }

    /**
     * 处理节点数据
     * @param sb
     * @param entry
     */
    public  void oneNode(StringBuffer sb, LinkedHashMap<String, Object> entry) {
        String userName = entry.get("user_id").toString();
        SysThirdAccount thirdAccount = sysThirdAccountService.lambdaQuery()
                .eq(SysThirdAccount::getThirdUserId, String.valueOf(entry.get("user_id"))).one();
        if (ObjectUtil.isNotEmpty(thirdAccount)){
            LoginUser user = sysBaseAPI.getUserById(thirdAccount.getSysUserId());
            if (ObjectUtil.isNotEmpty(user)){
                userName = user.getRealname();
            }
        }
        String type = ObjectUtil.equal(entry.get("type").toString(), "AND") ? "【并签】" : "【或签】";
        String status = ApprovaStateEnum.parse(String.valueOf(entry.get("status"))).getMsg();
        //sb.append(type);
        sb.append("["+status+"]");
        sb.append(userName);
    }

}